﻿using System.Text.RegularExpressions;
using Microsoft.SqlServer.Management.SqlStudio.Explorer;
using Microsoft.SqlServer.Management.UI.VSIntegration;
using Microsoft.SqlServer.Management.UI.VSIntegration.ObjectExplorer;

namespace CnSharp.SSMS.AddIn.Util
{
    public static class ObjectExplorerHelper
    {
        public static DbObjectContext GetContext()
        {
            var node = GetSelectedNode();
            return node == null ? null : GetContext(node);
        }

        public static DbObjectContext GetContext(INodeInformation node)
        {

            DbObjectContext context = null;
            var match = TryToMatch(ObjectNodeContextRegex.TableRegex, node, out context);
            if (context != null)
            {
                context.Name = match.Groups["Table"].Value;
                return context;
            }

            match = TryToMatch(ObjectNodeContextRegex.ViewRegex, node, out context);
            if (context != null)
            {
                context.Name = match.Groups["View"].Value;
                return context;
            }

            match = TryToMatch(ObjectNodeContextRegex.SpRegex, node, out context);
            if (context != null)
            {
                context.Name = match.Groups["StoredProcedure"].Value;
                return context;
            }

            TryToMatch(ObjectNodeContextRegex.DbRegexStart, node, out context);
            return context;
        }

        private static Match TryToMatch(Regex regex, INodeInformation node,out DbObjectContext context)
        {
            context = null;
            var match = regex.Match(node.Context);
            if (match.Success)
            {
                context = GetContext(match, node);
            }
            return match;
        }

        private static DbObjectContext GetContext(Match match,INodeInformation node)
        {
            var dbNode = new DbObjectContext
            {
                Server = match.Groups["Server"].Value,
                Database = match.Groups["Database"].Value
            };
            dbNode.ConnectionString = node.Connection.ConnectionString + ";Database=" + dbNode.Database;
            return dbNode;
        }

        private static ObjectExplorerService GetObjectExplorerService()
        {
            return (ObjectExplorerService)ServiceCache.ServiceProvider.GetService(typeof(IObjectExplorerService));
        }




        public static INodeInformation GetSelectedNode()
        {
            var objExplorerService = GetObjectExplorerService();

            // Get selection
            INodeInformation[] nodes;
            int nodeCount;
            objExplorerService.GetSelectedNodes(out nodeCount, out nodes);

            //objExplorerService.FindNode()
            return (nodeCount > 0 ? nodes[0] : null);
        }

        public static void LocateObject(string objectType, string name)
        {
            var dbNode = GetContext();
            if (dbNode == null)
                return;
            var objExplorerService = GetObjectExplorerService();
            var node = objExplorerService.FindNode(
                string.Format("Server[@Name='{0}']/Database[@Name='{1}']/{2}[@Name='{3}' and @Schema='dbo']",
                              dbNode.Server, dbNode.Database, objectType, name
                    ));
            if (node != null)
            {
                objExplorerService.SynchronizeTree(node);

                //var win = DocumentHelper.FindWindow("Object Explorer");//ObjectKind:{D114938F-591C-46CF-A785-500A82D97410}
                var win =
                    WindowHelper.FindWindow(
                        window => window.ObjectKind == "{D114938F-591C-46CF-A785-500A82D97410}");
                if(win != null)
                    win.Activate();
            }
        }


        //public static Project GetProject()
        //{
        //    var dte = ServiceCache.ExtensibilityModel;
        //    if (dte.Solution == null || dte.Solution.Projects == null || dte.Solution.Projects.Count < 1)
        //        return null;
        //    if (dte.SelectedItems.Count == 1 && dte.SelectedItems.Item(1).Project != null)
        //        return dte.SelectedItems.Item(1).Project;
        //    return null;
        //}

      
    }
}